<template>
    <el-dialog :model-value="props.isSetKeyword" :show-close="false" modal-class="customize-dialog" :append-to-body="true"
        :close-on-click-modal="false" align-center width="1000">
        <template #header="{ titleId, titleClass }">
            <div class="flex justify-between items-center dialog-header">
                <div class="flex items-center">
                    <h4 :id="titleId" :class="titleClass">关键词设置</h4>
                </div>
                <svg-icon size="16px" icon-class="close-line" @click="closeDialog"></svg-icon>
            </div>
        </template>
        <div>
            <div class="flex items-center friendly-tips">
                <svg-icon size="18px"
                    icon-class="information-2-fill"></svg-icon>友情提示：主关键词为本文章主要产品名称，可替换关键词为代替主关键词生成新的文章，最多可以填写<el-text type="danger">10</el-text>个。
            </div>
            <div class="pt-46px">
                <el-form ref="ruleFormRef" :rules="rules" label-width="120px">
                    <el-form-item label="文章主关键词" prop="mainKeyword">
                        <div class="w-150px">
                            <el-input ref="nameRef" v-model="state.mainKeyword" :disabled="checkIsMain()" placeholder="请输入文章主关键词" />
                        </div>
                    </el-form-item>
                    <el-form-item label="替换文章关键词" prop="name">
                        <div class="flex flex-wrap">
                            <div class="w-150px mr-12px mb-5px" v-for="(item, index) in state.keywords" :key="index"><el-input :disabled="checkIsReplace(state.keywords[index])" v-model="state.keywords[index]" /></div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="pl-120px pb-35px">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { getArticleKeywordsApi,articleKeywordSubmitApi } from '@/api/b2b'

const props = defineProps({
    isSetKeyword: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    },
    pid: {
        type: Number,
        default: 0
    },
    keyword: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['closeDialog'])

const state = reactive({
    mainKeyword: '',
    keywords: new Array<string>(10).fill(''),
    words:<string[]>[]
})

const rules = reactive({
    mainKeyword: [
        { min: 3, max: 35, required: true, message: '请输入文章标题', trigger: 'blur', validator: checkMainKeyword }
    ],
})

function checkMainKeyword(rule: any, value: any, callback: any) {
    
}

function closeDialog() {
    reset()
    emit('closeDialog')
}

async function handleConfirm(){
    //验证主关键词 + 替换关键词
    console.log(props.id,props.pid,state.mainKeyword,state.keywords.filter(Boolean).join('/'))
    if(!state.mainKeyword){
        return ElMessage.error('请输入文章主关键词')
    }else if(!state.keywords.filter(Boolean).length){
        return ElMessage.error('请输入替换关键词')
    }else{
        const res: ResType = await articleKeywordSubmitApi({
            id: props.id,
            pid: props.pid,
            zkey: state.mainKeyword,
            tkey: state.keywords.filter(Boolean).join('/')
        })
        if(res.code === 200){
            ElMessage.success('设置成功')
            reset()
            emit('closeDialog')
        }
    }
}

async function getArticleKeywords(){
    const res: ResType = await getArticleKeywordsApi({
        id: props.id,
        pid: props.pid
    })
    if(res.code === 200){
        state.mainKeyword = res.data.zkey
        if(res.data.tkey.length > 0){
            let keywords = res.data.tkey.split('/')
            keywords.forEach((item:string,index:number) => {
                state.keywords[index] = item
                state.words.push(item)
            })
        }else{
            state.keywords = new Array<string>(10).fill('')
            state.words = []
        }
    }
}

function checkIsMain(){
    if(!props.pid && state.keywords.length > 0){
        return false
    }else{
        return true
    }
}

function checkIsReplace(value:string):boolean{
    if(value === props.keyword){
        return false
    }
    const isPidValid = typeof props.pid === 'number' && props.pid > 0;
    return Boolean(isPidValid && value.length && state.words.includes(value))
}

function reset(){
    state.keywords = new Array<string>(10).fill('')
    state.mainKeyword = ''
    state.words = []
}

watch(() => props.isSetKeyword, () => { 
    getArticleKeywords()
})


</script>

<style scoped>

</style>

<!-- 关键词设置有三种情况 -->
<!-- 1、第一次设置 主关键词（唯一）， 替换文章关键词设置了几个，当前文章就会生成几个，并且每条替换文章的主关键词就是主文章里的替换关键词 -->
<!-- 2、关键词已存在，当前文档如果是主文章，主关键词和替换关键词可修改，也可新增替换关键词 -->
<!-- 3、关键词已存在，当前文档如果是替换文章，只能新增替换关键词,只能修改自己的替换关键词，不能修改主关键词和其他替换关键词 -->